package com.evan.webadmin.biz.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.evan.common.core.constant.SubjectTypeEnum;
import com.evan.common.core.exception.MyRuntimeException;
import com.evan.common.core.object.ResponseResult;
import com.evan.common.core.object.TokenData;
import com.evan.webadmin.biz.dao.EvluateRecordMapper;
import com.evan.webadmin.biz.dto.EvluateNewDtoFilter;
import com.evan.webadmin.biz.dto.EvluateRecordItemNewDto;
import com.evan.webadmin.biz.dto.EvluateRecordNewDto;
import com.evan.webadmin.biz.model.EvluateRecord;
import com.evan.webadmin.biz.model.EvluateSurvey;
import com.evan.webadmin.biz.service.IEvluateRecordService;
import com.evan.webadmin.biz.service.IEvluateSurveyService;
import com.evan.webadmin.biz.vo.EvluateRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Pavel
 * @since 2025-03-11
 */
@Service
public class EvluateRecordServiceImpl extends ServiceImpl<EvluateRecordMapper, EvluateRecord> implements IEvluateRecordService {

    @Autowired
    EvluateRecordMapper evluateRecordMapper;
    @Autowired
    IEvluateSurveyService evluateSurveyService;

    @Override
    public List<EvluateRecord> findByCondition(EvluateNewDtoFilter evluateFilter) {
        return Collections.emptyList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<EvluateRecordNewDto> record(EvluateRecordNewDto frontDto, HttpServletRequest request) {
        EvluateSurvey survey = evluateSurveyService.getById(frontDto.getSurveyId());
        if(survey == null){
            throw new MyRuntimeException("问卷不存在");
        }
        TokenData tokenData = (TokenData) request.getAttribute(TokenData.REQUEST_ATTRIBUTE_NAME);
        EvluateRecord evluateRecord = new EvluateRecord();
        evluateRecord.setSurveyId(survey.getId());
        evluateRecord.setSurveyName(survey.getSurveyName());
        evluateRecord.setUserId(tokenData.getUserId());
        evluateRecord.setUserName(tokenData.getShowName());
        List<EvluateRecordItemNewDto> list = frontDto.getRecords();
        Integer totalScore = list.stream().filter(item -> SubjectTypeEnum.SURVEY.getCode() == item.getType()).map(EvluateRecordItemNewDto::getScore).reduce(0, (x,y) -> x+y);
        evluateRecord.setTotalScore(totalScore);
        evluateRecord.setPersonnelType(frontDto.getPersonnelType());
        evluateRecord.setSurveyContent(JSONUtil.toJsonStr(frontDto.getRecords()));
        evluateRecord.setCreateTime(new Date());
        evluateRecordMapper.insert(evluateRecord);
        return ResponseResult.success(frontDto);
    }

    @Override
    public ResponseResult<EvluateRecordNewDto> exist(EvluateNewDtoFilter filter, HttpServletRequest request) {
        QueryWrapper<EvluateRecord> queryWrapper = new QueryWrapper<>();
        Long surveyId = filter.getSurveyId();
        EvluateSurvey survey;
        if(surveyId == null){
            survey = evluateSurveyService.findPublishedPaper();
            surveyId = survey.getId();
        }else{
            survey = evluateSurveyService.getById(surveyId);
        }

        if(surveyId == null){
            throw new MyRuntimeException("不存在发布问卷");
        }
        String userId = filter.getSelectUserId();
        if(!StringUtils.hasLength(userId)){
            TokenData tokenData = (TokenData) request.getAttribute(TokenData.REQUEST_ATTRIBUTE_NAME);
            userId = tokenData.getUserId();
        }

        queryWrapper.eq("survey_id", surveyId);
        queryWrapper.eq("user_id", userId);
        EvluateRecord evluateRecord = evluateRecordMapper.selectOne(queryWrapper);
        if (evluateRecord == null) {
            return ResponseResult.success(null);
        }
        EvluateRecordNewDto recordNewDto = new EvluateRecordNewDto();
        recordNewDto.setSurveyId(evluateRecord.getSurveyId());
        recordNewDto.setPersonnelType(evluateRecord.getPersonnelType());
        recordNewDto.setSurveyName(survey.getSurveyName());
        String surveyContent = evluateRecord.getSurveyContent();
        if (surveyContent != null) {
            List<EvluateRecordItemNewDto> list = JSONArray.parseArray(surveyContent, EvluateRecordItemNewDto.class);
            recordNewDto.setRecords(list);
        }
        return  ResponseResult.success(recordNewDto);
    }

    @Override
    public List<EvluateRecordVO> rankList(long surveyId) {
        return evluateRecordMapper.rankList(surveyId);
    }

    @Override
    public long existCount(long surveyId) {
        QueryWrapper<EvluateRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("survey_id", surveyId);
        queryWrapper.eq("delete_flag", 0L);
        return evluateRecordMapper.selectCount(queryWrapper);
    }
}
